<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1300" @ok="handleSubmit">
     <div style="width:100%;display:flex;padding:12px;">
        <BasicForm style="width:450px;" @register="registerForm" ref="formRef" ></BasicForm>
        <div style="width: 700px;height:300px;margin-left:20px;">
           
          <a-calendar
          :fullscreen="false"
          v-model:value="attendDateValue"
        >
          <template slot="headerRender">
            <div>
              <div class="calendar_select">
                <div class="calendar_s_select">
                </div>
              </div>
            </div>
          </template>
          <template #dateFullCellRender="{ current: value }">
            <div :class="getDateCss(value)"  v-on:click="handleSelectDate(value)">
              {{ value.date() }}
            </div>
          </template>
        </a-calendar>
        </div>
     </div>
     
  
  <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="科目信息" key="dormStorey" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="dormStorey"
          :loading="dormStoreyTable.loading"
          :columns="dormStoreyTable.columns"
          :dataSource="dormStoreyTable.dataSource"
          :height="300"
          :rowNumber="true"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="true"
          :toolbarConfig="{ btn: ['add',]}"
          >
          
            <template #myAction="props">
              <a-button @click="subjectRemoved(props)" >删除</a-button>
              
            </template>
            <template #costSlot="props">
              {{ props.row | handleGetCost(props.row) }}
            </template>
          </JVxeTable>
      </a-tab-pane>
    </a-tabs>
  </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref,reactive} from 'vue';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import { JVxeTable } from '/@/components/jeecg/JVxeTable'
    import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts'
    import {formSchema,subjectColumns} from '../CsCourseTheme.data';
    import {saveOrUpdate,subjectlist,deleteSubject,queryAttendDateByThemeId,getCost} from '../CsCourseTheme.api';
   
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const formDisabled = ref(false);
    const refKeys = ref(['dormStorey', ]);
    const activeKey = ref('dormStorey');
    const dormStorey = ref();
    const rowId = ref('');
    const tableRefs = {dormStorey, };
    const dormStoreyTable = reactive({
          loading: false,
          dataSource: [],
          columns:subjectColumns
    });
    const allChecked = ref(false);
    let selectDateArr = ref([]);
    let attendDateValue = ref('')
    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue}] = useForm({
        //labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 12}
    });
     //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        await reset();
        setModalProps({confirmLoading: false,showCancelBtn:data?.showFooter,showOkBtn:data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        formDisabled.value = !data?.showFooter;
        selectDateArr.value = []
        if (unref(isUpdate)) {
            //表单赋值
            rowId.value = data.record.id;
            data.record.beginAndEndDate=data.record.beginDate+','+data.record.endDate;
            queryAttendDateByThemeId({themeId:data.record.id}).then(res=>{
                  selectDateArr.value=res;
            });
            await setFieldsValue({
                ...data.record,
            });
             requestSubTableData(subjectlist, {themeId:data?.record?.id}, dormStoreyTable)
        }
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //方法配置
    const [handleChangeTabs,handleSubmit,requestSubTableData,formRef] = useJvxeMethod(requestAddOrEdit,classifyIntoFormData,tableRefs,activeKey,refKeys);

    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

    async function reset(){
      await resetFields();
      activeKey.value = 'dormStorey';
      dormStoreyTable.dataSource = [];
    }

    async function handleGetCost(row){
      let cost = 0
      await getCost({id:row.courseId}).then(res=>{
        cost = Number(res.cost)
      })
      //cost = 1;
      console.log("***");
      console.log(cost);
      return "0.01"
    }

    function handleSelectDate(val){
      let tempVal = val.format("YYYY-MM-DD")
      console.log(tempVal);
      let tempIndex = selectDateArr.value.findIndex(item=>{return item==tempVal})
      if(tempIndex==-1){
        selectDateArr.value.push(tempVal)
      }else{
        selectDateArr.value.splice(tempIndex,1)
      }

      console.log(selectDateArr.value);
    }

    const selectDate = (val) => {
      console.log(val);
    };
    const getDateCss = val=> {
      let _className = "dateBox";
      selectDateArr.value.forEach(item=>{
        if(item== val.format("YYYY-MM-DD")){
           _className = "selectBox";
        }
      })
      return _className;
    }

    function classifyIntoFormData(allValues) {
         let main = Object.assign({}, allValues.formValue)
         return {
           ...main, // 展开
           subjectlist: allValues.tablesValue[0].tableData,
         }
    }
 
    function subjectRemoved(e){
      console.log(e);
      // console.log(dormStoreyTable.dataSource);
      if(e.row.createTime){
          deleteSubject({
            id: e.rowId
          }).then(res=>{
             requestSubTableData(subjectlist, {themeId:rowId.value}, dormStoreyTable)
              // dormStorey.value?.removeRows(e.row, true);
          })
      }else{
        dormStorey.value?.removeRows(e.row, true);
      }

    }
    //表单提交事件
    async function requestAddOrEdit(values) {
        try {
            setModalProps({confirmLoading: true});
            //提交表单
            let data = values
            data.attendDate =selectDateArr.value
            await saveOrUpdate(data, isUpdate.value);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }
</script>

<style lang="less" scoped>
.dateBox{
   width:26px;
    height: 26px;
    margin: auto;
}
  .selectBox{
    color: #1890ff;
    border: 1px solid #1890ff;
    border-radius: 50%;
    width:26px;
    height: 26px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: auto;
  }

	/** 时间和数字输入框样式 */
    :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
</style>